<script lang="ts">
    import { Dropdown } from "../Dropdown";
    import type { SubMenuProps } from "./Menu";
    import { MenuContextKey, useMenuContext } from "./Menu.svelte";
    import { useClassList } from "../utils/useClassList";
    import { onMount, setContext } from "svelte";
    import { slide } from "svelte/transition";
    import MenuItem from "./MenuItem.svelte";

    const props: SubMenuProps = $props();

    if (!props.name) {
        console.warn("SubMenu need name prop");
    }

    let min = $state(false);
    const ctx: any = useMenuContext();
    const store = ctx.getStore();
    const open = $derived.by(() => {
        let isOpen = false;
        if (store.openKeys && props.name) {
            isOpen = store.openKeys[props.name];
        }
        return isOpen;
    });
    const classList = $derived(
        useClassList(props, "cm-menu-submenu", {
            "cm-menu-submenu-open": open,
        }),
    );

    const level = ctx.level;
    const parentName = ctx.parentName;

    $effect(() => {
        let flag = false;
        flag = store.min && parentName === "__root";
        min = flag;
    });

    const item = {
        name: props.name,
        parent: null,
        children: [],
    };
    if (ctx && props.name) {
        ctx.treeMap[props.name] = item;
        if (parentName === "__root") {
            ctx?.tree.push(item);
        } else {
            const parent = ctx.treeMap[parentName!];
            item.parent = parent;
            parent.children.push(item);
        }
    }

    const onSelect = () => {
        if (ctx?.dir() === "v") {
            ctx?.setOpen(props.name);
        }
    };

    const align = props.align || (ctx?.dir() === "h" ? "bottom" : "rightTop");

    setContext(MenuContextKey, { ...ctx, level: level + 1, parentName: props.name });
</script>

<li class={classList}>
    <!-- {#if min || ctx?.dir === "h"} -->
    <Dropdown {align} disabled={!(min || ctx?.dir() === "h")} theme={ctx?.theme} revers={false}>
        {#snippet menu()}
            <ul class="cm-menu-submenu-list" in:slide={{ duration: 200 }} out:slide={{ duration: 200 }}>
                {@render props.children?.()}
            </ul>
        {/snippet}
        <MenuItem icon={props.icon} cert isSubmenuTitle {parentName} onselect={onSelect}>{props.title}</MenuItem>
        {#if !(min || ctx?.dir() === "h")}
            {#if open}
                <ul class="cm-menu-submenu-list" in:slide={{ duration: 200 }} out:slide={{ duration: 200 }}>
                    {@render props.children?.()}
                </ul>
            {:else}
                <div style="display: none">
                    {@render props.children?.()}
                </div>
            {/if}
        {/if}
    </Dropdown>
</li>
